package com.js.foodordersystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.js.foodordersystem.mapper.DishMapper;
import com.js.foodordersystem.entity.Dish;
import com.js.foodordersystem.mapper.OrderItemMapper;
import com.js.foodordersystem.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.js.foodordersystem.util.Result;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 存储菜品信息(Dish)表服务实现类
 *
 * @author makejava
 * @since 2025-01-09 10:52:48
 */
@Service("dishService")
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public Result selectAll(Dish dish, Integer limit, Integer page) {
        List<Map<String, Object>> list = baseMapper.selectAll(dish, (page - 1) * limit, limit);
        for (Map<String, Object> map : list) {
            map.put("dishId", map.get("dishId").toString());
        }
        HashMap<String, Object> result = new HashMap<>();
        result.put("count", baseMapper.selectAllCount(dish));
        result.put("data", list);
        return Result.success(result);
    }

    @Override
    public List<Dish> getPopularDishes(int limit) {
        // 查询销量最高的菜品ID列表
        List<Long> popularDishIds = orderItemMapper.selectPopularDishIds(limit);

        // 如果订单详情中没有数据，返回随机菜品
        if (popularDishIds.isEmpty()) {
            return getRandomDishes(limit);
        }

        // 根据菜品ID列表查询菜品信息
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("dish_id", popularDishIds);
        List<Dish> popularDishes = baseMapper.selectList(queryWrapper);

        // 如果订单详情中的数据量小于 limit，随机补齐剩余菜品
        if (popularDishes.size() < limit) {
            int remaining = limit - popularDishes.size();
            List<Dish> randomDishes = getRandomDishes(remaining);
            popularDishes.addAll(randomDishes);
        }

        return popularDishes;
    }

    /**
     * 获取随机菜品
     *
     * @param limit 返回的记录条数
     * @return 随机菜品列表
     */
    private List<Dish> getRandomDishes(int limit) {
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.last("ORDER BY RAND() LIMIT " + limit);
        return baseMapper.selectList(queryWrapper);
    }
}

